package day04.actor

import akka.actor.{Actor, ActorRef, ActorSelection, ActorSystem, Props}
import akka.actor.Actor.Receive
import com.typesafe.config.ConfigFactory

/**
  * Created by root on 2018/11/26.
  */
class Woker extends Actor{


  /**
    * preStart 在构造器之后，receive方法执行之前执行一次
    */
  @scala.throws[Exception](classOf[Exception])
  override def preStart(): Unit = {
    //让worker跟master建立链接，并发送给master一个消息
    val masterProx: ActorSelection = context.actorSelection("akka.tcp://Master_actor_system@127.0.0.1:8888/user/Master")
    //拿到master的代理对象   发送消息
    masterProx.!("connect")

  }

  override def receive: Receive = {
    case "success" =>{
      println("a success msg from Master")
    }
  }
}

object Woker{
  def main(args: Array[String]): Unit = {
    val host = "127.0.0.1"
    val port ="9999"

    val confStr =
      s"""
         |akka.actor.provider = "akka.remote.RemoteActorRefProvider"
         |akka.remote.netty.tcp.hostname = $host
         |akka.remote.netty.tcp.port = $port
      """.stripMargin

    val config = ConfigFactory.parseString(confStr)
    // 创建 actorSystem(单例)
    val actorSystem = ActorSystem("Worker_actor_system",config)

    //通过创建的actorSystem 在创建actor    ,actor创建会执行声明周期方法
    val workerActor: ActorRef = actorSystem.actorOf(Props[Woker](),"Worker")




  }
}
